import {
  getOrderInfo,
  // applyOrder,
  getHistoryKeys,
  getHistoryOrderTitleList,
  publishOrder,
  getOrderList,
  getMoreOrderList,
  getSearchOrderList,
  getMoreSearchOrderList,
  getPublishOrderList,
  getMorePublishOrderList,
  getApplicationOrderList,
  addHistoryKeys,
  getBusinessList,
  getMoreApplicationOrderList
} from '../api/api'
import io from 'socket.io-client'
export default {
  namespaced: true,
  state: {
    socket: null,
    orderListMaxLen: 30,
    orderType: '0', // 箱子类型
    orderStatus: 1, // 箱子状态
    searchStr: '',
    searchList: [],
    busyPub: true,
    busyApp: true,
    bussList: [], // 装箱单
    orderInfo: {},
    orderDriver: [],
    orderList: [],
    falog: false, // 搜索状态
    newOrders: [],
    historyTags: [],
    publishOrderList: [],
    fabuOrderList: 15, // 我发布的下拉获取条数
    shenqingOrderList: 15, // 我申请的下拉获取条数
    applicationOrderList: [],
    historyOrderTitleList: [],
    updBlUnix: 0 // 更新运单列表，值为时间戳
  },
  mutations: {
    initOrderList (state, orderList) {
      state.orderList = orderList
    },
    initHistoryTags (state, historyTags) {
      state.historyTags = historyTags
    },
    resetSearch (state) {
      state.searchStr = ''
      state.searchList = []
      state.orderType = '0'
    },
    resetMyOrder (state) {
      state.orderStatus = ''
      state.publishOrderList = []
      state.applicationOrderList = []
    },
    resetOrderInfo (state) {
      state.orderInfo = {}
    },
    resetOrderList (state) {
      state.orderList = []
    },
    resetDriver (state) {
      state.orderDriver = []
    },
    resetHistoryOrder (state) {
      state.historyOrderTitleList = []
    }
  },
  actions: {
    initOrder ({ dispatch }) {
      dispatch('initOrderServer')
      dispatch('getHistoryKeys')
      dispatch('getHistoryOrderTitleList')
    },
    initOrderServer ({ state, rootState }) {
      state.socket = io('http://47.101.133.38:304')
      state.socket.on('connect', () => {
        console.log('订单服务连接成功')
      })
      state.socket.on('disconnect', () => {})
      if (rootState.user.UserType !== '4') {
        state.socket.on('box_message', (data) => {
          data.map(item => {
            console.log(rootState.user.UserType, 'usertype2222222222')
            if (rootState.user.UserType === '4') {
              return false
            }
            const patt1 = new RegExp(state.searchStr)
            const findKeys = state.orderList.findIndex((value) => {
              return value.Brief === item.Brief
            })
            const findMap = state.searchList.findIndex((value) => {
              return value.Brief === item.Brief
            })
            if (findKeys === -1) {
              if (state.orderType === '0' && state.searchStr === '') {
                state.orderList.unshift(item)
                document.getElementById('orderAudio').play()
              } else if (state.orderType === item.msgs && state.searchStr === '') {
                state.orderList.unshift(item)
                document.getElementById('orderAudio').play()
              }
            } else {
              state.orderList.forEach((value, index) => {
                if (value.Brief === item.Brief) {
                  state.orderList.splice(index, 1)
                  if (state.orderType === '0' && state.searchStr === '') {
                    state.orderList.unshift(item)
                    document.getElementById('orderAudio').play()
                  } else if (state.orderType === item.msgs && state.searchStr === '') {
                    console.log('推送消息分类', item)
                    state.orderList.unshift(item)
                    document.getElementById('orderAudio').play()
                  }
                }
              })
            }
            if (patt1.test(item.Brief) && state.searchStr !== '') {
              if (findMap === -1) {
                if (state.orderType === '0' && state.searchStr !== '') {
                  state.searchList.unshift(item)
                  document.getElementById('orderAudio').play()
                } else if (state.orderType === item.msgs && state.searchStr !== '') {
                  state.searchList.unshift(item)
                  document.getElementById('orderAudio').play()
                }
              } else {
                state.searchList.forEach((arr1, index) => {
                  if (arr1.Brief === item.Brief) {
                    state.searchList.splice(index, 1)
                    if (state.orderType === '0' && state.searchStr !== '') {
                      state.searchList.unshift(item)
                      document.getElementById('orderAudio').play()
                    } else if (state.orderType === item.msgs && state.searchStr !== '') {
                      state.searchList.unshift(item)
                      document.getElementById('orderAudio').play()
                    }
                  }
                })
              }
            }
            console.log('推送消息', state.orderType, data)
            if (state.orderList.length > state.orderListMaxLen) {
              state.orderList.splice(state.orderListMaxLen, state.orderList.length - state.orderListMaxLen)
            }
          })
        })
      }
    },
    sendOrderMessage ({ state }, orderMessage) {
      state.socket.emit('box_message', [orderMessage])
    },
    getOrderInfo ({ state, dispatch }, orderId) {
      getOrderInfo({
        MessageId: orderId
      }).then(res => {
        if (res.status === 200) {
          state.orderInfo = res.data[0]
          let len = res.mydriver.length
          for (let i = 0; i < len; i++) {
            state.orderDriver.push(res.mydriver[i].PlateNumber)
          }
        } else {
          dispatch('app/showToast', {
            text: res.msg
          }, { root: true })
        }
      }, err => {
        dispatch('app/showToast', {
          text: err
        }, { root: true })
      })
    },
    // 首页前30条
    getOrderList ({ state, dispatch, rootState }, orderType) {
      state.orderType = orderType
      if (rootState.user.UserType === '4') {
        return false
      }
      dispatch('app/showLoading', {}, { root: true })
      getOrderList({
        msgtype: state.orderType,
        siteId: '2'
      }).then(res => {
        dispatch('app/hideLoading', {}, { root: true })
        if (res.status === 200) {
          const data = res.data
          dispatch('app/loadMore', { listLength: data.length }, { root: true })
          state.orderList = data
        } else {
          dispatch('app/showToast', {
            text: res.msg
          }, { root: true })
        }
      }, err => {
        dispatch('app/showToast', {
          text: err
        }, { root: true })
      })
    },
    getMoreOrderList ({ state, dispatch }) {
      if (state.orderList.length < state.orderListMaxLen) {
        dispatch('app/loadMore', {}, { root: true })
        return false
      }
      dispatch('app/showLoading', {}, { root: true })
      getMoreOrderList({
        msgtype: state.orderType,
        datetime: state.orderList[state.orderList.length - 1].DateUpdated,
        siteId: '2'
      }).then(res => {
        dispatch('app/hideLoading', {}, { root: true })
        if (res.status === 200) {
          const data = res.data
          dispatch('app/loadMore', { listLength: data.length }, { root: true })
          state.orderList = state.orderList.concat(data)
        } else {
          dispatch('app/showToast', {
            text: res.msg
          }, { root: true })
        }
      }, err => {
        dispatch('app/showToast', {
          text: err
        }, { root: true })
      })
    },
    // 添加搜索历史
    addHistoryKeys ({state, dispatch}, hisorder) {
      addHistoryKeys({
        keywords: hisorder
      }).then(res => {
        if (res.status === 200) {
          const findIndex = state.historyTags.findIndex((item) => {
            return item === hisorder
          })
          if (findIndex === -1) {
            state.historyTags.unshift(hisorder)
          }
        } else {
          dispatch('app/showToast', {
            text: res.msg
          }, { root: true })
        }
      }, err => {
        dispatch('app/showToast', {
          text: err
        }, { root: true })
      })
    },
    getHistoryKeys ({ state, dispatch }) {
      getHistoryKeys({
        number: 10
      }).then(res => {
        if (res.status === 200) {
          let data = res.data
          let tags = []
          data.map(item => {
            tags.push(item.KeywordText)
          })
          state.historyTags = tags
        } else {
          dispatch('app/showToast', {
            text: res.msg
          }, { root: true })
        }
      }, err => {
        dispatch('app/showToast', {
          text: err
        }, { root: true })
      })
    },
    getSearchOrderList ({ state, dispatch, rootState }) {
      state.falog = !state.falog
      if (rootState.user.UserType === '4') {
        return false
      }
      dispatch('app/showLoading', {}, { root: true })
      getSearchOrderList({
        keywords: state.searchStr,
        msgtype: state.orderType,
        siteId: '2'
      }).then(res => {
        dispatch('app/hideLoading', {}, { root: true })
        if (res.status === 200) {
          const data = res.data
          dispatch('app/loadMore', { listLength: data.length }, { root: true })
          state.searchList = res.data
        } else {
          dispatch('app/showToast', {
            text: res.msg
          }, { root: true })
        }
      }, err => {
        dispatch('app/showToast', {
          text: err
        }, { root: true })
      })
    },
    getMoreSearchOrderList ({ state, dispatch, rootState }) {
      if (rootState.user.UserType === '4') {
        return false
      }
      if (state.searchList.length < state.orderListMaxLen) {
        dispatch('app/loadMore', {}, { root: true })
        return false
      }
      getMoreSearchOrderList({
        datetime: state.searchList[state.searchList.length - 1].DateUpdated,
        keywords: state.searchStr,
        msgtype: state.orderType,
        siteId: '2'
      }).then(res => {
        if (res.status === 200) {
          const data = res.data
          dispatch('app/loadMore', { listLength: data.length }, { root: true })
          state.searchList = state.searchList.concat(res.data)
        } else {
          dispatch('app/showToast', {
            text: res.msg
          }, { root: true })
        }
      }, err => {
        dispatch('app/showToast', {
          text: err
        }, { root: true })
      })
    },
    getBusinessList ({state, dispatch, rootState}, { starTtime, endTime }) {
      getBusinessList({
        page: 1,
        num: 100,
        blno: '',
        userName: '',
        starTtime: starTtime,
        endTime: endTime,
        number: '',
        sendSomeoneId: rootState.user.uid
      }).then(res => {
        dispatch('app/hideLoading', {}, { root: true })
        if (res.status === 200) {
          const data = res.data
          dispatch('app/loadMore', { listLength: data.length }, { root: true })
          state.bussList = res.data
          console.log(res.data, '我的运单')
        } else {
          dispatch('app/showToast', {
            text: res.msg
          }, { root: true })
        }
      }, err => {
        dispatch('app/showToast', {
          text: err
        }, { root: true })
      })
    },
    getPublishOrderList ({ state, dispatch, rootState }, orderStatus) {
      state.orderStatus = orderStatus
      if (rootState.user.UserType === '4') {
        return false
      }
      dispatch('app/showLoading', {}, { root: true })
      getPublishOrderList({
        State: state.orderStatus,
        number: 15
      }).then(res => {
        dispatch('app/hideLoading', {}, { root: true })
        if (res.status === 200) {
          const data = res.data
          dispatch('app/loadMore', { listLength: data.length }, { root: true })
          state.publishOrderList = res.data
          if (state.publishOrderList.length === 15) {
            state.busyPub = false
            state.busyApp = true
          } else {
            state.busyPub = true
          }
        } else {
          dispatch('app/showToast', {
            text: res.msg
          }, { root: true })
        }
      }, err => {
        dispatch('app/showToast', {
          text: err
        }, { root: true })
      })
    },
    getMorePublishOrderList ({ state, dispatch, rootState }) {
      if (rootState.user.UserType === '4') {
        return false
      }
      if (state.publishOrderList.length < 15) {
        return false
      }
      if (state.fabuOrderList < 15) {
        return false
      }
      dispatch('app/showLoading', {}, { root: true })
      getMorePublishOrderList({
        datetime: state.publishOrderList[state.publishOrderList.length - 1].DateUpdated,
        State: state.orderStatus,
        number: 15
      }).then(res => {
        dispatch('app/hideLoading', {}, { root: true })
        if (res.status === 200) {
          const data = res.data
          state.fabuOrderList = data.length
          dispatch('app/loadMore', { listLength: data.length }, { root: true })
          state.publishOrderList = state.publishOrderList.concat(res.data)
        } else {
          dispatch('app/showToast', {
            text: res.msg
          }, { root: true })
        }
      }, err => {
        dispatch('app/showToast', {
          text: err
        }, { root: true })
      })
    },
    getApplicationOrderList ({ state, dispatch, rootState }, orderStatus) {
      state.orderStatus = orderStatus
      if (rootState.user.UserType === '4') {
        return false
      }
      dispatch('app/showLoading', {}, { root: true })
      getApplicationOrderList({
        State: state.orderStatus,
        number: 15
      }).then(res => {
        dispatch('app/hideLoading', {}, { root: true })
        if (res.status === 200) {
          const data = res.data
          dispatch('app/loadMore', { listLength: data.length }, { root: true })
          state.applicationOrderList = res.data
          if (state.applicationOrderList.length === 15) {
            state.busyApp = false
            state.busyPub = true
          } else {
            state.busyApp = true
          }
        } else {
          dispatch('app/showToast', {
            text: res.msg
          }, { root: true })
        }
      }, err => {
        dispatch('app/showToast', {
          text: err
        }, { root: true })
      })
    },
    getMoreApplicationOrderList ({ state, dispatch, rootState }) {
      if (rootState.user.UserType === '4') {
        return false
      }
      if (state.applicationOrderList.length < 15) {
        return
      }
      if (state.shenqingOrderList.length < 15) {
        return
      }
      dispatch('app/showLoading', {}, { root: true })
      getMoreApplicationOrderList({
        datetime: state.applicationOrderList[state.applicationOrderList.length - 1].DateUpdated,
        State: state.orderStatus,
        number: 15
      }).then(res => {
        dispatch('app/hideLoading', {}, { root: true })
        if (res.status === 200) {
          const data = res.data
          state.shenqingOrderList = data.length
          dispatch('app/loadMore', { listLength: data.length }, { root: true })
          state.applicationOrderList = state.applicationOrderList.concat(data)
        } else {
          dispatch('app/showToast', {
            text: res.msg
          }, { root: true })
        }
      }, err => {
        dispatch('app/showToast', {
          text: err
        }, { root: true })
      })
    },
    getHistoryOrderTitleList ({ state, dispatch }) {
      getHistoryOrderTitleList({
        msgtype: '0',
        number: 10
      }).then(res => {
        if (res.status === 200) {
          const data = res.data
          const titleList = []
          data.map(item => {
            titleList.push(item.Brief)
          })
          state.historyOrderTitleList.push(titleList)
        } else {
          dispatch('app/showToast', {
            text: res.msg
          }, { root: true })
        }
      }, err => {
        dispatch('app/showToast', {
          text: err
        }, { root: true })
      })
    },
    publishOrder ({ state, dispatch }, orderInfo) {
      return new Promise((resolve, reject) => {
        publishOrder(orderInfo).then(res => {
          if (res.status === 200) {
            state.historyOrderTitleList[0].unshift(orderInfo.Brief)
            if (state.historyOrderTitleList[0][0].length > 10) {
              state.historyOrderTitleList[0].splice(9, 1)
            }
            resolve(res.data[0])
          } else {
            dispatch('app/showToast', {
              text: res.msg
            }, { root: true })
          }
        }, err => {
          dispatch('app/showToast', {
            text: err
          }, { root: true })
        })
      })
    }
  }
}
